<?php

namespace app\admin\controller\facrm;

use app\admin\model\AuthGroup;
use app\admin\model\facrm\Contract;
use app\admin\model\facrm\contract\Receivables;
use app\common\controller\Backend;
use fast\Date;
use fast\Tree;
use think\Config;

/**
 * 控制台
 *
 * @icon fa fa-dashboard
 * @remark 用于展示当前系统中的统计数据、统计报表及重要实时数据
 */
class Dashboard extends Backend
{

    protected $groupList=[];
    protected $groupdata=[];
    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Admin');

        $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
        $this->childrenGroupIds = $this->auth->getChildrenGroupIds(true);

        $this->groupList = collection(AuthGroup::where('id', 'in', $this->childrenGroupIds)->select())->toArray();
        Tree::instance()->init( $this->groupList);
        if ($this->auth->isSuperAdmin()) {
            $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
            foreach ($result as $k => $v) {
                $this->groupdata[$v['id']] = $v['name'];
            }
        } else {
            $result = [];
            $groups = $this->auth->getGroups();
            foreach ($groups as $m => $n) {
                $childlist = Tree::instance()->getTreeList(Tree::instance()->getTreeArray($n['id']));
                $temp = [];
                foreach ($childlist as $k => $v) {
                    $temp[$v['id']] = $v['name'];
                }
                $result[__($n['name'])] = $temp;
            }
            $this->groupdata = $result;
        }

        $this->view->assign('groupdata', $this->groupdata);
        $this->assignconfig("admin", ['id' => $this->auth->id]);

    }
    /**
     * 查看
     */
    public function index()
    {
        if ($this->request->isAjax()){
            $ajax_type=$this->request->param('ajax_type');
            $temp_type=$this->request->param('type');
            switch ($ajax_type){
                case 'achievement':
                    $achievement=$this->achievement(
                        $this->request->param('row_config'),
                        $this->request->param('row_year'),
                        $this->request->param('row_month',0,'intval'),
                        3,$this->auth->id,$this->auth->id
                    );

                    $this->success('','',$achievement);
                case 'team_achievement':
                    $achievement=$this->achievement(
                        $this->request->param('row_config'),
                        $this->request->param('row_year'),
                        $this->request->param('row_month',0,'intval'),
                        2,$this->childrenGroupIds,$this->childrenAdminIds
                    );

                    $this->success('','',$achievement);
                case 'getAchievementEchart':
                    //$temp_type是区分团队的还是个人的
                    $this->success('', '', [
                        $temp_type => $this->getAchievementEchart(false,0,($temp_type=='team_achievement'?$this->childrenAdminIds:$this->auth->id))
                    ]);
                case 'getRecordEchartData':
                    //$temp_type是区分团队的还是个人的
                    $this->success('', '', [
                        $temp_type => $this->getRecordEchartData(false,0,($temp_type=='team_record'?$this->childrenAdminIds:$this->auth->id))
                    ]);

            }
            return $this->error("访问出错");
        }

        //自己的start
        //当天开始时间
        $start_time=strtotime(date("Y-m-d",time()));
        //当天结束之间
        $end_time=$start_time+60*60*24;
       
        $filter_w['owner_user_id'] = $this->auth->id;
        $customerModel = model('\app\admin\model\facrm\Customer');
        $cluesModel = model('\app\admin\model\facrm\Clues');
        //需要联系客户
        $communicate=$customerModel->where('next_time','between',[1,$end_time])->where($filter_w)->count();

        //需要联系的线索
        $clues_num=$cluesModel->where('next_time','between',[1,$end_time])->where($filter_w)->count();

        //将要过期的用户
        $lose_num=count($customerModel->getLose($this->auth->id));

        $businessModel = model('\app\admin\model\facrm\Business');
        $business=$businessModel->where('next_time','between',[1,$end_time])->where($filter_w)->count();
        //是否有合同权限
        $contract_return=$contract_expire=0;
        if($this->auth->check('facrm/contract/index')){
            $contractModel = model('\app\admin\model\facrm\Contract');
            $filter_w['check_status']=2;
            //快过期和过期合同
            $contract_expire=$contractModel->where('end_time','between',[1,$end_time+(30*86400)])->where('expire_handle',0)->where($filter_w)->count();
            //待回款合同
            $contract_return=$contractModel->where("money","exp",">return_money")->where($filter_w)->count();
        }
        $year=date("Y",time());

        $achievement=$this->achievement(1,$year,0,3,$this->auth->id,$this->auth->id);
        $this->view->assign([
            'communicate'=>$communicate,
            'lose_num'=>$lose_num,
            'business'=>$business,
            'contract_expire'=>$contract_expire,
            'contract_return'=>$contract_return,
            'clues_num'=>$clues_num,
            'achievement'=>$achievement,
        ]);
        $erchart = [
            'achievement' => $this->getAchievementEchart(false,0,$this->auth->id),
            'record' => $this->getRecordEchartData(false,0,$this->auth->id),
        ];
        $this->view->assign([
            'erchart' => $erchart,
        ]);
        $this->assignconfig(['achievement'=>$achievement]);
        //自己的end

        //团队的
        $filter_w=array();
        $filter_w['owner_user_id'] =['in',$this->childrenAdminIds];

        //需要联系客户
        $team_communicate=$customerModel->where('next_time','between',[1,$end_time])->where($filter_w)->count();
        //需要联系的线索
        $team_clues_num=$cluesModel->where('next_time','between',[1,$end_time])->where($filter_w)->count();
        //需要联系的联系人
        //$team_communicate=$customerModel->where('next_time','between',[1,$end_time])->where($filter_w)->count();
        //将要过期的用户
        $team_lose_num=count($customerModel->getLose($this->childrenAdminIds));

        $team_business=$businessModel->where('next_time','between',[1,$end_time])->where($filter_w)->count();
        //是否有合同权限
        $team_contract_return=$team_contract_expire=0;
        if($this->auth->check('facrm/contract/index')){
            $contractModel = model('\app\admin\model\facrm\Contract');
            $filter_w['check_status']=2;
            //快过期和过期合同
            $team_contract_expire=$contractModel->where('end_time','between',[1,$end_time+(30*86400)])->where('expire_handle',0)->where($filter_w)->count();
            //待回款合同
            $team_contract_return=$contractModel->where("money","exp",">return_money")->where($filter_w)->count();
        }

        $team_achievement=$this->achievement(1,$year,0,2,$this->childrenGroupIds,$this->childrenAdminIds);
        $this->view->assign([
            'team_communicate'=>$team_communicate,
            'team_lose_num'=>$team_lose_num,
            'team_business'=>$team_business,
            'team_contract_expire'=>$team_contract_expire,
            'team_contract_return'=>$team_contract_return,
            'team_clues_num'=>$team_clues_num,
            'team_achievement'=>$team_achievement,
        ]);
        $team_erchart = [
            'team_achievement' => $this->getAchievementEchart(false,0,$this->childrenAdminIds),
            'team_record' => $this->getRecordEchartData(false,0,$this->childrenAdminIds),
        ];
        $this->view->assign([
            'team_erchart' => $team_erchart,
        ]);
        $this->assignconfig(['team_achievement'=>$team_achievement]);


        //团队的end

        return $this->view->fetch();
    }



    /**
     * 业绩指标
     * @param $config 1=>'合同金额',2=>'回款金额'
     * @param $year 年份
     * @param $month 1~12月份 0代表年份
     * @param $type 2部门3员工
     * @param $type_id 对应type对象ID
     * @return array
     */
    private function achievement($config,$year,$month,$type,$type_id,$admin_id){
        $config_arr=[1=>'合同金额',2=>'回款金额'];
        $month_arr=[0=>'yeartarget',1=>"january",2=>"february",3=>"march",4=>"april",5=>"may",6=>"june"
            ,7=>"july",8=>"august",9=>"september",10=>"october",11=>"november",12=>"december"
        ];
        if (!isset($month_arr[$month])||!isset($config_arr[$config])){
            $this->error("参数有误");
        }

        if (!is_numeric($year)){
            $this->error("年份有误");
        }
        $achievementModel=new \app\admin\model\facrm\Achievement();
        //获取已完成情况
        //当天开始时间
        list($start_time,$end_time)=$this->mFristAndLast($year,$month);
        //获取业绩目标
        if ( $type==3){
            //员工业绩
            $yeartarget=$achievementModel->where('type',$type)->where('type_id',$type_id)
                ->where('config',$config)
                ->where('year',$year)->value($month_arr[$month]);
            $contract_money=Contract::where('check_status',2)->where('order_admin_id',$admin_id)
                ->where('order_time','between',[$start_time,$end_time])
                ->sum('money');
            $receivables_money=Receivables::where('check_status',2)->where('order_admin_id',$admin_id)
                ->where('return_time','between',[$start_time,$end_time])
                ->sum('money');
        }else{
            //部门业绩
            $yeartarget=$achievementModel->where('type',$type)->where('type_id','in',$type_id)
                ->where('config',$config)
                ->where('year',$year)->sum($month_arr[$month]);
            $contract_money=Contract::where('check_status',2)->where('order_admin_id','in',$admin_id)
                ->where('order_time','between',[$start_time,$end_time])
                ->sum('money');
            $receivables_money=Receivables::where('check_status',2)->where('order_admin_id','in',$admin_id)
                ->where('return_time','between',[$start_time,$end_time])
                ->sum('money');
        }

        $achievement=[
            'name'=>$config_arr[$config],
            'year'=>$year,
            'yeartarget'=>$yeartarget?$yeartarget:0,
            'contract_money'=>$contract_money,
            'receivables_money'=>$receivables_money,
            'complete_percent'=>$yeartarget>0?round(($config==1?$contract_money:$receivables_money)/$yeartarget*100,2):0,
        ];

        return $achievement;

    }

    /**
     * 获取时间的开始和结束时间
     * @param int $y
     * @param int $m
     * @return array
     */
    private  function mFristAndLast($y=0,$m=0){

        $y = $y ? $y : date('Y');
        $e_m=$m ? $m :12;//如果月份不存在说明想获取一整年，取结束月份为12月
        $m = $m ? $m :1;//如果月份不存在说明想获取一整年，取开始月份为1月
        $d = date('t', strtotime($y.'-'.$m));
        return array(strtotime($y.'-'.$m),mktime(23,59,59,$e_m,$d,$y));
    }

    /**
     * ECHART业绩情况统计
     * @param bool $is_ajax
     * @return array|bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function  getAchievementEchart($is_ajax = true,$group_id=0,$owner_user_id=0){
        $startDate = $this->request->param('start_date', null);
        $endDate = $this->request->param('end_date', null);
        $owner_user_ids='';
        if ($owner_user_id > 0) {
            $owner_user_ids=$owner_user_id;
        }elseif($group_id&&$group_id>0){
            Tree::instance()->init($this->groupList);
            $groupIds=Tree::instance()->getChildrenIds($group_id,true);

            $authGroupList = \app\admin\model\AuthGroupAccess::
            field('uid,group_id')
                ->where('group_id', 'in', $groupIds)
                ->select();
            foreach ($authGroupList as $k => $v) {
                if (in_array($v['uid'],$owner_user_ids)) continue;
                $owner_user_ids[] = $v['uid'];
            }
            if (!$owner_user_ids){
                $this->error("没有数据");
            }
        }
        $contractModel = new \app\admin\model\facrm\Contract();
        $data=$contractModel->getAchievementEchart($startDate,$endDate,$owner_user_ids);

        if ($is_ajax) {
            $this->success('', '', [
                'achievement' => $data
            ]);
        } else {
            return $data;
        }
    }



    /**
     * Echart跟进趋势
     * @return bool
     */
    private function getRecordEchartData($is_ajax = true,$group_id=0,$owner_user_id=0)
    {
        $startDate = $this->request->param('start_date', null);
        $endDate = $this->request->param('end_date', null);

        $owner_user_ids='';
        if ($owner_user_id > 0) {
            $owner_user_ids=$owner_user_id;
        }elseif($group_id&&$group_id>0){
            Tree::instance()->init($this->groupList);
            $groupIds=Tree::instance()->getChildrenIds($group_id,true);

            $authGroupList = \app\admin\model\AuthGroupAccess::
            field('uid,group_id')
                ->where('group_id', 'in', $groupIds)
                ->select();
            foreach ($authGroupList as $k => $v) {
                if (in_array($v['uid'],$owner_user_ids)) continue;
                $owner_user_ids[] = $v['uid'];
            }
            if (!$owner_user_ids){
                $this->error("没有数据");
            }
        }

        $recordModel = new \app\admin\model\facrm\Record();
        $data=$recordModel->getRecordEchartData($startDate,$endDate,$owner_user_ids);
        if ($is_ajax) {
            $this->success('', '', [
                'record' => $data
            ]);
        } else {
            return $data;
        }
    }

}
